<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="盘点计划" prop="inventoryPlanId">
        <el-select v-model="formItem.inventoryPlanId" class="select_input" placeholder="请选择资产来源">
          <el-option v-for="(item) in createdPlans" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="formItem.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="责任人" prop="userId">
        <el-input v-model="formItem.userName" placeholder="请选择任务责任人">
          <i slot="suffix" class="el-input__icon el-icon-s-custom" @click="handleUserIconClick" />
        </el-input>
      </el-form-item>

      <el-divider content-position="left">盘点范围</el-divider>
      <el-form-item label="位置" prop="locationCodes">
        <treeselect
          v-model="formItem.locationCodes"
          :multiple="true"
          :options="availableLocations"
          value-consists-of="LEAF_PRIORITY"
        />
      </el-form-item>
      <el-form-item label="类型" prop="assetTypeCodes">
        <treeselect
          v-model="formItem.assetTypeCodes"
          :multiple="true"
          :options="availableTypes"
          value-consists-of="LEAF_PRIORITY"
        />
      </el-form-item>
      <el-form-item label="部门" prop="orgCodes">
        <treeselect
          v-model="formItem.orgCodes"
          :multiple="true"
          :options="availableOganizations"
          placeholder="请选择部门"
          :flat="true"
          value-consists-of="ALL_WITH_INDETERMINATE"
          @select="selcetOrg"
          @deselect="deSelcetOrg"
          @input="clearOrg"
        />
      </el-form-item>

    </el-form>
    <SelectDialog title="选择任务负责人" :show="userSelDialogFormVisible" :append-to-body="true" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" />
    </SelectDialog>
  </div>
</template>

<script>
import {
  create,
  update,
  detail
} from '@neu/dcam-ui/api/inventoryDuty'
import UsersPage from '@neu/auth-ui/views/users/tables'
import { createdList } from '@neu/dcam-ui/api/inventoryPlan'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import { tree } from '@neu/dcam-ui/api/location'
import { tree as typeTree } from '@neu/dcam-ui/api/assetType'
import { tree as organizationsTree } from '@neu/auth-ui/api/organization'

// 定义一个表单原始项
const formItem = {
  name: '',
  status: 'created',
  userId: '',
  userName: '',
  inventoryPlanId: '',
  inventoryPlanName: '',
  locationCodes: [],
  assetTypeCodes: [],
  orgCodes: [],
  orgNames: []
}
export default {
  name: 'InventoryPlanEditForm',
  components: {
    SelectDialog,
    UsersPage
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      /** 是否显示用户选择对话框 */
      userSelDialogFormVisible: false,
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 位置树
      availableLocations: [],
      // 类型树
      availableTypes: [],
      // 组织树
      availableOganizations: [],
      // 已创建状态的盘点计划
      createdPlans: [],
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '任务名称不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 100) {
              callback(new Error('最多可输入100个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        userId: [{
          required: true,
          message: '任务责任人不能为空',
          trigger: 'change'
        }],
        inventoryPlanId: [{
          required: true,
          message: '盘点计划不能为空',
          trigger: 'change'
        }]
      },
      modal: true
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler(newVal, oldVal) {
        this.fetch()
      },
      immediate: true
    }
  },
  created() {
    tree().then(response => {
      this.availableLocations = response.data
    })
    typeTree().then(response => {
      this.availableTypes = response.data
    })
    organizationsTree().then(response => {
      this.availableOganizations = [response.data]
    })
    createdList().then(response => {
      this.createdPlans = response.data
    })
    this.fetch()
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      // 至少选择一个范围
      if (this.formItem.locationCodes.length === 0 && this.formItem.assetTypeCodes.length === 0 && this.formItem.orgCodes.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择盘点范围!'
        })
        return false
      }
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    /** 选择用户按钮 */
    handleUserIconClick() {
      this.userSelDialogFormVisible = true
    },
    /** 责任人选择ok */
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个责任人',
          type: 'error'
        })
      }
      if (users.length < 1) {
        this.formItem.userId = ''
        this.formItem.userName = ''
      } else {
        this.formItem.userId = users[0].id
        this.formItem.userName = users[0].name ? users[0].name : users[0].username
      }
      this.userSelDialogFormVisible = false
    },
    // 选择组织机构
    selcetOrg(value) {
      this.formItem.orgNames.push(value.title)
    },
    // 取消组织机构
    deSelcetOrg(value) {
      this.formItem.orgNames = this.formItem.orgNames.filter(ele => ele !== value.title)
    },
    // 按钮取消
    clearOrg(value) {
      if (!value) this.formItem.orgNames = []
    },
    /** 责任人选择取消 */
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    /** 重置 */
    reset() {
      this.$refs.myform.resetFields()
      this.formItem.userName = ''
      // this.formItem = { ...formItem }
    }
  }
}
</script>
